package com.xwltz.common.phone.algorithm;

import com.xwltz.common.phone.base.IspEnum;
import com.xwltz.common.phone.base.PhoneBase;
import com.xwltz.common.phone.base.PhoneModel;

import java.util.Optional;

/**
 * @description SequenceAlgorithm
 * @information on version 1.0 be created by @xwltz at 2021/11/08 15:47
 */

public class SequenceAlgorithm extends PhoneBase {

	@Override
	public Optional<PhoneModel> getInfo(String phoneNumber) {
		if (checkInvalidPhoneNumber(phoneNumber)) return Optional.empty();
		int attributionIdentity = checkPhoneNumberIsNumber(phoneNumber);
		if (attributionIdentity == 0) return Optional.empty();

		for (int i = indicesStartOffset; i < originalByteBuffer.limit(); i = i + 8 + 1) {

			originalByteBuffer.position(i);
			int phonePrefix = originalByteBuffer.getInt();
			int infoStart = originalByteBuffer.getInt();
			byte ispMark = originalByteBuffer.get();
			if (phonePrefix == attributionIdentity) {
				IspEnum isp = IspEnum.of(ispMark).orElse(IspEnum.UNKNOWN);
				originalByteBuffer.position(infoStart);
				// while ((originalByteBuffer.get()) != 0) {}
				int infoEnd = originalByteBuffer.position() - 1;
				originalByteBuffer.position(infoStart);
				int length = infoEnd - infoStart;
				byte[] bytes = new byte[length];
				originalByteBuffer.get(bytes, 0, length);
				String oriString = new String(bytes);
				PhoneModel model = parse(phoneNumber, oriString, isp);
				return Optional.of(model);
			}
		}
		return Optional.empty();
	}
}
